import Head from 'next/head'
import Image from 'next/image'
import axios from "axios";
import {useState} from "react";
import {BsSearch} from "react-icons/bs";
import Weather from "../components/Weather";
import Spinner from "../components/Spinner";

export default function Home() {

    const [city, setCity] = useState("");
    const [weather, setWeather] = useState({});
    const [isLoading, setIsLoading] = useState(false);
    const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${process.env.NEXT_PUBLIC_API_KEY}&units=metric`


    const fetchWeather = (e) => {
        e.preventDefault()
        setIsLoading(true)
        axios.get(url).then((res) => {
            setWeather(res.data)
        })
        setCity("");
        setIsLoading(false);
    };

    if (isLoading) {
        return <Spinner/>
    } else {
        return (<>
            <Head>
                <title>Weather App</title>
                <meta name="description" content="Generated by create next app"/>
                <meta name="viewport" content="width=device-width, initial-scale=1"/>
                <link rel="icon" href="/favicon.ico"/>
            </Head>

            <div className="absolute top-0 right-0 left-0 bottom-0 bg-black/40 z-[1]"/>
            <Image
                src="https://images.unsplash.com/photo-1569429512518-44dad00e88db?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80"
                layout="fill"
                alt="Background"
                className="object-cover"
            />

            <div
                className="relative flex justify-between items-center max-w-[500px] mt-10 w-full m-auto text-white z-10">
                <form
                    onSubmit={fetchWeather}
                    className="flex justify-between items-center w-full m-auto p-3 bg-transparent border border-gray-300 text-white rounded-2xl">
                    <div>
                        <input
                            type="text"
                            placeholder="Search city"
                            className="bg-transparent border-none text-white focus:outline-none text-2xl"
                            onChange={(e) => setCity(e.target.value)}
                        />
                    </div>
                    <button><BsSearch size={20}/></button>
                </form>
            </div>

            {weather.main && <Weather data={weather}/>}
        </>)
    }
}
